package com.zhiyou100.loans.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class JDBCUtil {
	//数据库四大件
	private static final String DRIVER="com.mysql.jdbc.Driver";
	private static final String URL="jdbc:mysql://192.168.218.210:3306/loans";
	private static final String USER="root";
	private static final String PASSWORD="root";
	//jdbc的通用对象
	private static Connection conn=null;
	private static PreparedStatement ps=null;
	private static ResultSet rs=null;

	static{
		try {
			Class.forName(DRIVER);
			conn=DriverManager.getConnection(URL, USER, PASSWORD);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 用于数据库查询
	 * @param sql 需要传入的sql语句
	 * @param objs 需要传入的参数数组
	 * @return 返回查询的结果集
	 */
	public ResultSet query(String sql,Object[] objs){
		try {
			ps = conn.prepareStatement(sql);
			
			for(int i=0;i<objs.length;i++){
				ps.setObject(i+1, objs[i]);
			}
			rs=ps.executeQuery();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return rs;
	}

	/**
	 * 用于数据库的增删改
	 * @param sql 需要传入的sql语句
	 * @param objs 需要传入的参数数组
	 * @return 返回受影响的行数，失败返回0
	 */
	public int update(String sql,Object[] objs){
		int a=0;
		try {
			ps = conn.prepareStatement(sql);
			for(int i=0;i<objs.length;i++){
				ps.setObject(i+1, objs[i]);
			}
			a=ps.executeUpdate();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return a;
	}
	/**
	 * 关闭资源
	 */
	public void close(){
		try {
			if(rs!=null){
				rs.close();
			}
			if(ps!=null){
				ps.close();
			}
			if(conn!=null){
				conn.close();
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
